
#import "MYShopSearchScreenView.h"
#import "MYShopSearchScreenCollViewCell.h"
#import "MYNewsBaseScreenModel.h"
#define kcollViewCellW ((selectTableViewW-62) / 3.0)
#define selectTableViewW (kYQPScreenWidth * (296.0/375))
#define kSELECTHEADERBTN_BASE_TAG 11000
@interface MYShopSearchScreenView ()<UIGestureRecognizerDelegate,UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView * collView;

@property (nonatomic, copy) YQPSearchScreenResultBlack resultBlack;
@property (nonatomic, copy) MYSearchScreenCancelBlack cancelBlack;
///所有筛选属性
@property (strong, nonatomic) NSMutableArray *attrValueArray;

/// 品牌id数组
@property (strong, nonatomic) NSMutableArray *brandIdsArray;

@property (nonatomic, strong) MYShopSearchScreenPriceTextFieldCell *textFieldCell;

@end

@implementation MYShopSearchScreenView

static NSString *headReusableCell = @"YQPCollectionHeadReusableView";

+ (void)showShopSearchScreenViewWithCatalog3Id:(NSString *)catalog3Id ResultBlack
:(YQPSearchScreenResultBlack)resultBlack
cancelBlack:(MYSearchScreenCancelBlack)cancelBlack {
    MYShopSearchScreenView *screenView = [[MYShopSearchScreenView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    screenView.backgroundColor = HexColorA(0x000000, 0.2);//HexColor(0xF3F5F9);
    screenView.resultBlack = resultBlack;
    screenView.cancelBlack = cancelBlack;
    screenView.catalog3Id = catalog3Id;
    
    [screenView showSelctTableView];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.attrValueArray = NSMutableArray.new;
        self.brandIdsArray = NSMutableArray.new;
        self.attrIdsArray = NSMutableArray.new;

        /*tableView下移20个点的问题*/
        if (@available(iOS 11.0, *)) {
            self.collView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
        self.backgroundColor = HexColorA(0x000000, 0.2);//HexColor(0xF3F5F9);
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelSelctTableView)];
        tap.delegate = self;
        [self addGestureRecognizer:tap];
        [self addSubview:self.collView];
    }
    return self;
}

- (void)setCatalog3Id:(NSString *)catalog3Id
{
    _catalog3Id = catalog3Id;
    [self.attrValueArray removeAllObjects];
    if (catalog3Id) {
        [self getGoodAttrValuesApi];
    }

}

#pragma mark - 搜索品牌属性
- (void)getGoodAttrValuesApi
{
    NSString *url = [NSString stringWithFormat:@"%@%@",kGET_GOOD_ATTRVALUE_INFO_URL,self.catalog3Id];
    if (self.isNewsScreen) {
        url = [NSString stringWithFormat:@"%@%@",kGET_INFORMATION_CATEGORY_SORT_URL,self.catalog3Id];
    }
    
    [YQPNetWorkingManager sendGetRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
            [self.attrValueArray removeAllObjects];
            if (self.isNewsScreen) {
                NSArray *attrValueArray = [MYNewsBaseScreenModel mj_objectArrayWithKeyValuesArray:responseObject.data];
                [self.attrValueArray addObjectsFromArray:attrValueArray];
            }else{
                YQPGoodAttrValueModel *model = YQPGoodAttrValueModel.new;
                model.attrName = kYQLS(@"价格区间");
                model.attrValueList = @[@""];
                [self.attrValueArray addObject:model];
                NSArray *attrValueArray = [YQPGoodAttrValueModel mj_objectArrayWithKeyValuesArray:responseObject.data];
                [self.attrValueArray addObjectsFromArray:attrValueArray];
            }
            
            [self.collView reloadData];
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error)
    }];
    
}

-(void)showSelctTableView {
    //1. 获取当前应用的主窗口
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    [keyWindow addSubview:self];
    // 浮现动画
    [UIView animateWithDuration:0.3 animations:^{
        self.collView.left = (kYQPScreenWidth-selectTableViewW);
    }];
    
}
#pragma mark - 移除侧拉屏并传递平台品牌属性到商品列表
-(void)cancelSelctTableView {
    
    if (self.cancelBlack) {
        self.cancelBlack();
    }
    // 关闭动画
    [UIView animateWithDuration:0.2 animations:^{
        self.collView.left = (kYQPScreenWidth+selectTableViewW);
    } completion:^(BOOL finished) {
        if ([self.delegate respondsToSelector:@selector(didSelectGoodItemGetBrandIds:andMinPrice:andMaxPrice:)]) {
            if (self.isNewsScreen) {
                
                //NSMutableArray *screenArr = @[].mutableCopy;
                NSMutableArray *IDArr = @[].mutableCopy;
                for (MYNewsBaseScreenModel *screenModel in self.attrValueArray) {
                    //NSMutableDictionary *screenDict = @{}.mutableCopy;//[NSMutableDictionary dictionary];
//                    NSMutableArray *IDArr = @[].mutableCopy;
                    for (MYNewsBaseScreenSubclassModel *subclassModel   in screenModel.informationAttrValueList) {
                        if (subclassModel.isSelected) {
//                            screenDict[@"informationAttrId"] = screenModel.informationAttrId;
                            [IDArr addObject:subclassModel.informationValueId];
                        }
                    }
//                    if (screenDict.allKeys.count > 0) {
//                        screenDict[@"informationValueIdList"] = IDArr.copy;
//                        [screenArr addObject:screenDict];
//                    }
                }
                
                [self.delegate didSelectGoodItemGetBrandIds:IDArr.copy andMinPrice:nil andMaxPrice:nil];
            }else{
                NSString *priceMin = self.textFieldCell.priceMinTextField.text;
                NSString *priceMax = self.textFieldCell.priceMaxTextField.text;
                if ([priceMin doubleValue] > [priceMax doubleValue] ) {
                    self.textFieldCell.priceMaxTextField.text = priceMin;
                    self.textFieldCell.priceMinTextField.text = priceMax;
                }
                [self.delegate didSelectGoodItemGetBrandIds:self.brandIdsArray andMinPrice:self.textFieldCell.priceMinTextField.text andMaxPrice:self.textFieldCell.priceMaxTextField.text];
            }
        }

        [self removeFromSuperview];
    }];
}

#pragma mark - UITextFieldDelegate结束编辑收回键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self endEditing:YES];
    return YES;
}

#pragma mark -- <UICollectionViewDelegate,UICollectionViewDataSource>
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.attrValueArray.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.isNewsScreen) {
        MYNewsBaseScreenModel *newsScreenModel = nil;
        if (section < self.attrValueArray.count) {
            newsScreenModel = self.attrValueArray[section];
        }
        
        if (newsScreenModel.isShow) {
            return newsScreenModel.informationAttrValueList.count;
        }
        return 0;
    }else{
        if (section == 0) {
            return 1;
        }
        YQPGoodAttrValueModel *model = self.attrValueArray[section];
        if (model.isShow) {
            return [model.attrValueList count];
        }
        return 0;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
       viewForSupplementaryElementOfKind:(NSString *)kind
                             atIndexPath:(NSIndexPath *)indexPath {
    // You can make header an ivar so we only ever create one
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
    //和判断复用一样
        MYShopSearchScreenHeaderView * head = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headReusableCell forIndexPath:indexPath];
        if (self.isNewsScreen) {
            MYNewsBaseScreenModel *newsScreenModel = nil;
            if (indexPath.section < self.attrValueArray.count) {
                newsScreenModel = self.attrValueArray[indexPath.section];
            }
            head.titleLb.text = newsScreenModel.informationAttrName;
            head.selectBtn.selected = newsScreenModel.isShow;
            
        }else{
            YQPGoodAttrValueModel *model = self.attrValueArray[indexPath.section];
            head.titleLb.text = model.attrName;
            head.selectBtn.hidden = (indexPath.section == 0);
            head.selectBtn.selected = model.isShow;
        }
        head.selectBtn.tag = kSELECTHEADERBTN_BASE_TAG + indexPath.section;
        [head.selectBtn addTarget:self action:@selector(headerShowAction:) forControlEvents:(UIControlEventTouchUpInside)];
        return head;
    }else{

    }
    return nil;
}

//设置头视图的尺寸，如果想要使用头视图，则必须实现该方法
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{

    return CGSizeMake(kScreenWidth - selectTableViewW, 77);

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.isNewsScreen) {
        MYNewsBaseScreenModel *screenModel = self.attrValueArray[indexPath.section];
        MYNewsBaseScreenSubclassModel *model = screenModel.informationAttrValueList[indexPath.row];
        MYShopSearchScreenSpecificationsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MYShopSearchScreenSpecificationsCell" forIndexPath:indexPath];
        cell.titleLb.text = model.informationValueName;
        cell.contentView.layer.cornerRadius = 4;
        cell.contentView.clipsToBounds = true;
        cell.isSelectedCell = model.isSelected;
        return cell;
    }else{
        if (indexPath.section == 0) {
            MYShopSearchScreenPriceTextFieldCell *textFieldCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MYShopSearchScreenPriceTextFieldCell" forIndexPath:indexPath];
            textFieldCell.priceMaxTextField.delegate = self;
            textFieldCell.priceMinTextField.delegate = self;
            self.textFieldCell = textFieldCell;
            return textFieldCell;
        }else{
            YQPGoodAttrValueModel *goodModel = self.attrValueArray[indexPath.section];
            YQPAttrValueListModel *model = goodModel.attrValueList[indexPath.row];
            MYShopSearchScreenSpecificationsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MYShopSearchScreenSpecificationsCell" forIndexPath:indexPath];
            cell.titleLb.text = model.valueName;
            cell.contentView.layer.cornerRadius = 4;
            cell.contentView.clipsToBounds = true;
            cell.isSelectedCell = model.isSelected;
            return cell;
        }
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isNewsScreen) {
        return CGSizeMake(kcollViewCellW,38);
    }
    if (indexPath.section == 0) {
        return CGSizeMake(kScreenWidth - kcollViewCellW, 63);
    }
    return CGSizeMake(kcollViewCellW,38);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 12.0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 19.0;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.isNewsScreen) {
        MYNewsBaseScreenModel *screenModel = self.attrValueArray[indexPath.section];
        MYNewsBaseScreenSubclassModel *subclassModel = screenModel.informationAttrValueList[indexPath.row];
        subclassModel.isSelected = !subclassModel.isSelected;
        
    }else{
        if (indexPath.section == 0) {
            return;
        }
        
        YQPGoodAttrValueModel *model = self.attrValueArray[indexPath.section];
        YQPAttrValueListModel *attrModel = model.attrValueList[indexPath.row];
        attrModel.isSelected = !attrModel.isSelected;
        
        NSLog(@"section:%@ row:%@",model.ID,attrModel.ID);
        

        if (attrModel.isSelected) {
            NSMutableDictionary *attrValuedic = [NSMutableDictionary dictionary];
            [attrValuedic setObject:model.ID forKey:@"attrId"];
            [attrValuedic setObject:attrModel.ID forKey:@"attrValueId"];
            [self.brandIdsArray addObject:attrValuedic];
        }else{
            for (NSDictionary *dict in self.brandIdsArray) {
                if ([dict[@"attrId"] isEqualToString:model.ID]) {
                    [self.brandIdsArray removeObject:dict];
                    break;
                }
            }
            
        }
    }
        
    [self.collView reloadData];
    
}

#pragma mark - 返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isNewsScreen) {
        return YES;
    }
    if (indexPath.section == 0) {
        return NO;
    }
    return YES;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isNewsScreen) {
        return YES;
    }
    if (indexPath.section == 0) {
        return NO;
    }
    return YES;
}

#pragma mark -- <UICollectionViewDelegate,UICollectionViewDataSource> end
#pragma mark --展开与收缩
-(void)headerShowAction:(UIButton *)sender {
    NSInteger section = sender.tag - kSELECTHEADERBTN_BASE_TAG;
    if (self.isNewsScreen) {
        MYNewsBaseScreenModel *screenModel = self.attrValueArray[section];
        screenModel.isShow = !screenModel.isShow;
    }else{
        YQPGoodAttrValueModel *model = self.attrValueArray[section];
        model.isShow = !model.isShow;
    }
    [self.collView reloadData];
}
#pragma makr --lazy
-(UICollectionView *)collView {
    if (!_collView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.sectionInset = UIEdgeInsetsMake(0, 12, 0, 12);
        _collView = [[UICollectionView alloc] initWithFrame:CGRectMake((kYQPScreenWidth+selectTableViewW), 0, selectTableViewW, kYQPScreenHeight) collectionViewLayout:layout];
        _collView.contentInset = UIEdgeInsetsMake(0, 0, 20, 0);
        _collView.backgroundColor = UIColor.whiteColor;
        _collView.delegate = self;
        _collView.dataSource = self;
        _collView.showsVerticalScrollIndicator = NO;
        //_collView.bounces = NO;
        [_collView registerNib:[UINib nibWithNibName:@"MYShopSearchScreenHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headReusableCell];
        [_collView registerNib:[UINib nibWithNibName:@"MYShopSearchScreenPriceTextFieldCell" bundle:nil] forCellWithReuseIdentifier:@"MYShopSearchScreenPriceTextFieldCell"];

        [_collView registerNib:[UINib nibWithNibName:@"MYShopSearchScreenSpecificationsCell" bundle:nil] forCellWithReuseIdentifier:@"MYShopSearchScreenSpecificationsCell"];
        //实现多选必须实现这个方法
        _collView.allowsMultipleSelection = YES;
    }
    return _collView;
}
#pragma mark --lazy end

#pragma mark - 对screenView的手势的响应
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），
//    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"] || [NSStringFromClass([touch.view class]) isEqualToString:@"_UITableViewHeaderFooterContentView"] || [NSStringFromClass([touch.view class]) isEqualToString:@"YQBaseTableView"] || [NSStringFromClass([touch.view class]) isEqualToString:@"UICollectionView"]) {
//        // cell 不需要响应 父视图的手势，保证didselect 可以正常
//        return NO;
//    }
    
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"MYShopSearchScreenView"]) {
        return YES;
    }
    
    
    //默认都需要响应
    return  NO;
}

@end
